//app.js
const qiniu = require("/utils/qiniu.min.js");
const mtjwxsdk = require('./utils/mtj-wx-sdk.js');
if (!Array.prototype.findIndex) {
  require('./utils/array-findIndex')
}
// var ald = require('./utils/ald-stat.js');
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    if (!wx.getStorageSync('uid')) {
      wx.setStorageSync('uid', '')
    }
  },
  redirectIfNotPermit: function () {
  },
  getLocation: function (options) {
    wx.getLocation({
      type: options.type || 'gcj02',
      altitude: true,
      success: function (res) {
        options.success && options.success(res);
      },
      fail: function (res) {
        options.fail && options.fail(res);
      }
    });
  },
  getUserInfo: function (cb, refresh) {
    var that = this;
    if (this.globalData.userInfo && !refresh) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        fail: function (res) {
          that.redirectIfNotPermit();
        },
        success: function (res) {
          var userCode = res.code,
            uid = wx.getStorageSync('uid');
          if (userCode && (uid == undefined || uid == '')) {
            that.redirectIfNotPermit();
          } else {
            that.req({
              url: 'blessmini/user/getUserInformation',
              method: 'POST',
              success: function (res) {
                console.log(res)
                that.globalData.userInfo = res.data;
                console.log(that.globalData.userInfo)
                if (res.data.telphone) {
                  typeof cb == "function" && cb(that.globalData.userInfo);
                } else {

                }

              }
            });
          }
        }
      })
    }
  },
  req: function (cfg) {
    var that = this,
      url = this.globalData.url + cfg.url;
    if (!cfg.noLoading) {
      wx.showLoading({
        title: '加载中',
      })
    }
    var realUrl = cfg.purl ? cfg.purl : url;
    var uid = wx.getStorageSync('uid');
    if (uid || uid == '') {
      if (realUrl.indexOf("?uid=") == -1) {
        realUrl += -1 == realUrl.indexOf("?") ? "?" : "&";
        realUrl += "uid=" + uid
      }
    }
    wx.request({
      url: realUrl,
      data: cfg.data,
      method: cfg.method ? cfg.method : 'POST',
      header: {
        'api-client': '0a1c968f172411ea995200163e05ff66',
        'api-version': '1.3.7',
      },
      success: function (res) {
        console.log(res, 111)
        if (!cfg.noLoading) {
          wx.hideLoading();
        }
        if (res && res.statusCode == 200) {
          if (res.data.code == 401) {
            that.redirectIfNotPermit();
          } else {
            cfg.success && cfg.success(res.data);
            if (res.data.code == 500) {
              that.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 3000
              })
            }
          }
        } else if (res.statusCode == 404) {
          that.showToast({
            title: '网络出错，请检查你的网络稍后再试',
            icon: "none",
            duration: 3000
          })
        } else {
          that.showToast({
            title: '网络出错，请检查你的网络稍后再试',
            icon: "none"
          })
        }
      },
      fail: function (a) {
        if (!cfg.noLoading) {
          wx.hideLoading();
        }
        that.showToast({
          title: '网络出错，请检查你的网络稍后再试',
          icon: "none"
        })
      },
      complete: function (res) {
        var requestData = {
          url: realUrl,
          data: cfg.data,
          response: res
        };
        console.log(requestData);
        wx.stopPullDownRefresh();
      }
    });
  },
  uploadFile: function (cfg) {
    console.log(cfg)
    var that = this,
      url = this.globalData.url + cfg.url;
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: cfg.purl ? cfg.purl : url,
      filePath: cfg.filePath,
      name: 'file',
      header: {
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        wx.hideLoading();
        if (res && res.statusCode == 200) {
          if (res.data.code == 401) {
            that.redirectIfNotPermit();
          } else {
            cfg.success(JSON.parse(res.data));
          }
        } else {
          that.showToast({
            title: '上传失败',
          })
        }
      },
      fail: function (a) {
        wx.hideLoading();
        that.showToast({
          title: '上传失败，请稍后再试',
          icon: "none"
        })
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    });
  },
  getNameByIdLabel(id, arr) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr[i].children.length; j++) {
        var arrChild = arr[i].children[j];
        if (arrChild.id == id) {
          return arrChild.text.trim();
        }
      }
    }
    return '';
  },
  uploadToQiNiu: function (config) {
    var that = this;
    // 交给七牛上传
    that.getQiNiuToken(function (data) {
      qiniu.upload(config.filePath, config.success, config.error ? config.error : function (r) { }, {
        uploadURL: 'https://upload.qiniup.com',
        region: 'ECN',
        domain: data.qiniuDomain,
        uptoken: data.upToken,
      })
    });


  },
  //获取七牛云上传授权
  getQiNiuToken(fun) {
    this.req({
      url: 'wechat/image/uploadApplication',
      data: {},
      method: 'POST',
      success: function (res) {
        if (res.code == 200) {
          typeof fun == "function" && fun(res.data);
        } else {
          wx.showToast({
            title: '获取文件上传权限失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onShow: function (e) {
    let that = this;
    wx.getSystemInfo({
      success: res => {
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          that.globalData.isIphoneX = true
        } else {
          that.globalData.isIphoneX = false
        }
      }
    })
  },
  showToast: function (cfg) {
    wx.showToast(cfg);
  },
  globalData: {
    userInfo: null,
    // 测试
    activityMiniAppId: 'wx41c81e0c8b670ad8',
    activityMiniEnvVersion: 'trial',
    url: 'https://test.yiqilaiwang.com/',
    // 正式
    // activityMiniAppId: 'wx15f071f49d1edf94',
    // activityMiniEnvVersion: 'release',
    // // url: 'https://www.yiqilaiwang.com/',
    // url: 'https://demo.yiqilaiwang.com/',
  }
});

/**
 * 定义克隆方法
 */
Object.defineProperty(
  Object.prototype,
  'clone', {
  value: function () {
    var cloneSelf = {};
    for (var key in this) {
      cloneSelf[key] = this[key];
    }
    return cloneSelf;
  },
  writable: false,
  enumerable: false,
  configurable: false
});